var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var app = express.createServer();
var io = require('socket.io').listen(app);
app.listen(3000);
/*
mongoose.connect('mongodb://localhost/some-js');

var User = new Schema({
  name: { type: String },
  age: { type: Number, min: 18, index: true }
});

var UserModel = mongoose.model('user', User);

app.post('/s/',function(req,res){
  switch(req.param('method')){
  case 'put':
  var user = new UserModel();
  user.name = req.param('name');
  user.age = req.param('age');
  user.save(function(err) {
    if(err)
    console.log('ERROR: user save' + err);
  });
  break;
  case 'find':
  UserModel.find({name:req.param('name')},function(err,docs) {
    if(!err)
    res.send(JSON.stringify(docs));
    else
    console.log('ERROR: user find' + err);
  });
  break;
  }
});
app.post('/login/',function(req,res){
  console.log('login\t' + req.param('login'));
  console.log('pass\t' + req.param('pass'));
});
app.post('/register/',function(req,res){
  console.log('login\t' + req.param('login'));
  console.log('pass\t' + req.param('pass'));
  console.log('pass_r\t' + req.param('pass'));
});
*/
io.sockets.on('connection', function(socket) {  
  var ID = (socket.id).toString().substr(0, 5);
  var time = (new Date).toLocaleTimeString();
  socket.json.send({'event': 'connected', 'name': ID, 'time': time});
  socket.broadcast.json.send({'event': 'userJoined', 'name': ID, 'time': time});
  socket.on('message', function (msg) {
    var time = (new Date).toLocaleTimeString();
    socket.json.send({'event': 'messageSent', 'name': ID, 'text': msg, 'time': time});
    socket.broadcast.json.send({'event': 'messageReceived', 'name': ID, 'text': msg, 'time': time})
  });
  socket.on('disconnect', function() {
    var time = (new Date).toLocaleTimeString();
    io.sockets.json.send({'event': 'userSplit', 'name': ID, 'time': time});
  });
});
